package net.rain.common;

import cn.hutool.core.util.StrUtil;
import net.rain.common.CurrentUser;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static net.rain.utils.RainConstants.LOGIN_USER_KEY;
import static net.rain.utils.RainConstants.LOGIN_USER_TTL;

/**
 * <p>
 * RefreshTokenInterceptor
 * <p>
 *
 * @author 春江花朝1秋月夜
 * @since 2023/8/15
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate=stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token =request.getHeader("authorization");//前端封装好的请求头需要携带这个东西
        if (StrUtil.isBlank(token)){
            return true;
        }
        //获取用户
        String key=LOGIN_USER_KEY+token;
        Map<Object,Object> userMap=stringRedisTemplate.opsForHash().entries(key);
        if (userMap.isEmpty()){
            return true;
        }
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
        CurrentUser.removeUser();
    }
}
